﻿using Autofac;

namespace RpcCentral.Common
{
    public class UnityHelper
    {
        private static Autofac.IContainer _Container = null;
        [ThreadStatic]
        private static IocScope _CurrentScope;

        public static void Init(Action<IocBuffer> initAction)
        {
            using(IocBuffer buffer = new IocBuffer())
            {
                buffer.Init();
                initAction(buffer);
                _Container = buffer.Build();
            }
        }
        public static IocScope CreateScore()
        {
            if (_CurrentScope == null)
            {
                ILifetimeScope lifetime = _Container.BeginLifetimeScope();
                _CurrentScope = new IocScope(lifetime, _Disposable);
                return _CurrentScope;
            }
            else
            {
               return _CurrentScope.CreateScore();
            }
        }
        private static void _Disposable(ILifetimeScope scope)
        {
            _CurrentScope = null;
        }

        public static T Resolve<T>()
        {
            if (_CurrentScope == null)
            {
                return _Container.Resolve<T>();
            }
            return _CurrentScope.Resolve<T>();
        }
        public static T Resolve<T>(string name)
        {
            if (_CurrentScope == null)
            {
                return _Container.ResolveKeyed<T>(name);
            }
            return _CurrentScope.Resolve<T>(name);
        }
    }
}
